﻿Public Class frmLayout

    Public DefaultLayoutName As String 'so caller can set initial value
    Private PriorLayoutName As String 'so can save settings after change selection
    Private FillingForm As Boolean = False

    Private Sub frmLayout_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        If chkHide.Checked Then SaveSetting(REGAPP, frmInfoMsg.SECTIONNAME, Me.Text, chkHide.Checked)
    End Sub

    Private Sub frmLayout_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If Not chkAuto.Checked Then
            Dim SomeSelected As Boolean = False
            For r As Integer = 0 To cboRows.Text - 1
                For c As Integer = 0 To cboCols.Text - 1
                    If GetCombo(c, r).Text <> "None" Then SomeSelected = True
                Next
            Next
            If Not SomeSelected Then
                WarningMsg("You must either automatically assign graphs to cells or select one or more graphs to be printed within the cells.")
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub frmLayout_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        chkHide.Checked = GetSetting(REGAPP, frmInfoMsg.SECTIONNAME, "Page Setup", "False")
        Dim lst As New Generic.List(Of String)
        lst.Add("None")
        For t As Integer = 0 To GraphForm.TabGraph.TabCount - 2
            lst.Add(GraphForm.TabGraph.TabPages(t).Text)
        Next
        lst.Add(CALIBRATIONSTRING)
        For r As Integer = 0 To 2
            For c As Integer = 0 To 1
                With GetCombo(c, r)
                    .Items.Clear()
                    .Items.AddRange(lst.ToArray)
                    .SelectedIndex = 0
                End With
            Next
        Next
        FillLayoutList()
        RefreshForm()
    End Sub

    Private Sub FillLayoutList()
        cboLayout.Items.Clear()
        For Each Layout As clsLayout In Layouts.Values
            cboLayout.Items.Add(Layout.Name)
        Next
        cboLayout.SelectedIndex = IIf(cboLayout.Items.Count = 0, -1, 0)
        cboRows.Enabled = cboLayout.SelectedIndex <> -1
        cboCols.Enabled = cboLayout.SelectedIndex <> -1
        For r As Integer = 0 To 2
            For c As Integer = 0 To 1
                GetCombo(c, r).Enabled = cboLayout.SelectedIndex <> -1
            Next
        Next
        If cboLayout.Items.Contains(DefaultLayoutName) Then cboLayout.Text = DefaultLayoutName
    End Sub

    Private Sub cboLayout_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles cboLayout.SelectedIndexChanged
        SaveLayout(PriorLayoutName)

        FillingForm = True

        With Layouts(cboLayout.Text)
            cboRows.Text = .NumRows
            cboCols.Text = .NumCols
            chkAuto.Checked = .AutoAssign
            sclPage.Minimum = 0
            sclPage.Value = 0
            sclPage.Maximum = .PageContents.Count - 1
            optPortrait.Checked = False
            optLandscape.Checked = False
            If .Landscape Then optLandscape.Checked = True Else optPortrait.Checked = True

            With .Margins
                txtLeft.Text = .Left / 100
                txtRight.Text = .Right / 100
                txtTop.Text = .Top / 100
                txtBottom.Text = .Bottom / 100
            End With
            txtRowCol.Text = .RowColMargin
            chkBorders.Checked = .DrawBorders
        End With

        FillingForm = False

        RefreshForm() 'fill all at once now

        PriorLayoutName = cboLayout.Text
    End Sub

    Private Sub btnNew_Click(sender As Object, e As System.EventArgs) Handles btnNew.Click
        Dim s As String = InputBox("Enter the name of the new layout:", "New Layout", "Layout " & Layouts.Count)
        If s <> "" Then
            For Each layout As clsLayout In Layouts.Values
                If layout.Name = s Then
                    WarningMsg("That layout name already exists; please respecify.")
                    Exit Sub
                End If
            Next
            Layouts.Add(s, New clsLayout(s))
            FillLayoutList()
            cboLayout.Text = s
        End If
    End Sub

    Private Sub btnDelete_Click(sender As Object, e As System.EventArgs) Handles btnDelete.Click
        If WarningMsg("Are you sure you want to delete the layout: {0}?", cboLayout.Text) = Windows.Forms.DialogResult.OK Then
            Layouts.Remove(cboLayout.Text)
            FillLayoutList()
        End If
    End Sub

    Private Sub btnClose_Click(sender As Object, e As System.EventArgs) Handles btnClose.Click
        SaveLayout(cboLayout.Text)
        GraphForm.ActiveLayoutName = cboLayout.Text
        With Layouts(cboLayout.Text)
            GraphForm.PrintDoc.DefaultPageSettings.Landscape = .Landscape
            GraphForm.PrintDoc.DefaultPageSettings.Margins = .Margins
        End With
        Me.DialogResult = Windows.Forms.DialogResult.OK
        Close()
    End Sub

    Private Sub SaveLayout(LayoutName As String)
        If String.IsNullOrEmpty(LayoutName) OrElse Not Layouts.ContainsKey(LayoutName) Then Exit Sub
        With Layouts(LayoutName)
            If .Name = LayoutName Then
                .NumRows = Val(cboRows.Text)
                .NumCols = Val(cboCols.Text)
                'pane contents set when combo index changed
                .Landscape = optLandscape.Checked
                .AutoAssign = chkAuto.Checked
                With .Margins
                    .Left = Val(txtLeft.Text) * 100
                    .Right = Val(txtRight.Text) * 100
                    .Top = Val(txtTop.Text) * 100
                    .Bottom = Val(txtBottom.Text) * 100
                End With
                .RowColMargin = Val(txtRowCol.Text)
                .DrawBorders = chkBorders.Checked
                GraphForm._IsModified = True
            End If
        End With
    End Sub

    Private Sub cntl_Changed(sender As Object, e As System.EventArgs) Handles chkBorders.CheckedChanged, optPortrait.CheckedChanged, chkAuto.CheckedChanged, cboRows.SelectedIndexChanged, cboCols.SelectedIndexChanged
        RefreshForm()
    End Sub

    Private Sub RefreshForm()

        If FillingForm Then Exit Sub 'if setting control values while filling, want to avoid many calls caused by event handlers

        For r As Integer = 0 To 2
            With tblLayout.RowStyles(r)
                If r <= Val(cboRows.Text) - 1 Then
                    .SizeType = SizeType.Percent
                    .Height = 50
                Else
                    .SizeType = SizeType.Absolute
                    .Height = 0
                End If
            End With
        Next

        For c As Integer = 0 To 1
            With tblLayout.ColumnStyles(c)
                If c <= Val(cboCols.Text) - 1 Then
                    .SizeType = SizeType.Percent
                    .Width = 50
                Else
                    .SizeType = SizeType.Absolute
                    .Width = 0
                End If
            End With
        Next

        btnDelete.Enabled = cboLayout.SelectedIndex > 0 'do not allow deletion of Default

        With Layouts(cboLayout.Text)
            For r As Integer = 0 To 2
                For c As Integer = 0 To 1
                    GetCombo(c, r).Visible = Not chkAuto.Checked
                Next
            Next
        End With
        tblMultiPage.Visible = Not chkAuto.Checked

        With tblPreview
            .Visible = False
            If optPortrait.Checked Then
                .RowStyles(0).Height = 0
                .RowStyles(1).Height = 100
                .RowStyles(2).Height = 0
                .ColumnStyles(0).Width = 15
                .ColumnStyles(1).Width = 70
                .ColumnStyles(2).Width = 15
            Else
                .RowStyles(0).Height = 15
                .RowStyles(1).Height = 70
                .RowStyles(2).Height = 15
                .ColumnStyles(0).Width = 0
                .ColumnStyles(1).Width = 100
                .ColumnStyles(2).Width = 0
            End If
            .Visible = True
        End With

        tblLayout.CellBorderStyle = IIf(chkBorders.Checked, TableLayoutPanelCellBorderStyle.Single, TableLayoutPanelCellBorderStyle.None)

        With Layouts(cboLayout.Text)
            sclPage.Minimum = 0
            sclPage.Maximum = .PageContents.Count - 1
            sclPage.Value = 0
        End With

        UpdatePage()
        UpdateCaption()

    End Sub

    Private Function GetCombo(Col As Integer, Row As Integer) As ComboBox
        If Row = 0 And Col = 0 Then Return cboC0R0
        If Row = 0 And Col = 1 Then Return cboC1R0
        If Row = 1 And Col = 0 Then Return cboC0R1
        If Row = 1 And Col = 1 Then Return cboC1R1
        If Row = 2 And Col = 0 Then Return cboC0R2
        If Row = 2 And Col = 1 Then Return cboC1R2
        Return Nothing
    End Function

    Private Sub cbo_SelectionChangeCommitted(sender As Object, e As System.EventArgs) Handles cboC0R0.SelectionChangeCommitted, cboC0R1.SelectionChangeCommitted, cboC0R2.SelectionChangeCommitted, cboC1R0.SelectionChangeCommitted, cboC1R1.SelectionChangeCommitted, cboC1R2.SelectionChangeCommitted
        For c As Integer = 0 To clsLayout.MaxCols - 1
            For r As Integer = 0 To clsLayout.MaxRows - 1
                If GetCombo(c, r) Is sender Then
                    If GetCombo(c, r).Text = CALIBRATIONSTRING Then
                        With New frmCalibrationRpt
                            clsCalibration.TryParseCalibrationString(Layouts(cboLayout.Text).PageContents(sclPage.Value).Item(c, r), .DefaultCalibration, .DefaultBranch, .DefaultStations, .DefaultParameters)
                            If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then 'save specifications for calibration report (must be arguments for clsCalibration.CreateReport)
                                Layouts(cboLayout.Text).PageContents(sclPage.Value).Item(c, r) = clsCalibration.GetCalibrationString(.cboCalibration.Text, .cboBranch.Text, .cboStation.Text, .cboParameter.Text)
                            Else
                                GetCombo(c, r).SelectedIndex = 0 'if cancel set to None
                            End If
                        End With
                    Else
                        Layouts(cboLayout.Text).PageContents(sclPage.Value).Item(c, r) = GetCombo(c, r).Text
                    End If
                    Exit Sub
                End If
            Next
        Next
    End Sub

    Private Sub sclPage_ValueChanged(sender As Object, e As System.EventArgs) Handles sclPage.ValueChanged
        If sclPage.Value = -1 Then Exit Sub
        UpdatePage()
        UpdateCaption()
    End Sub

    Private Sub btnRemovePage_Click(sender As System.Object, e As System.EventArgs) Handles btnRemovePage.Click
        With Layouts(cboLayout.Text).PageContents
            If .Count > 1 Then
                .RemoveAt(sclPage.Value)
                sclPage.Maximum -= 1
            Else
                WarningMsg("You must keep at least one page in your layout.")
            End If
        End With
        UpdateCaption()
    End Sub

    Private Sub btnAddPage_Click(sender As Object, e As System.EventArgs) Handles btnAddPage.Click
        With Layouts(cboLayout.Text).PageContents
            .Add(New clsPaneContents)
            sclPage.Maximum += 1
            sclPage.Value = sclPage.Maximum
        End With
        UpdateCaption()
    End Sub

    Private Sub UpdatePage()
        With Layouts(cboLayout.Text)
            For r As Integer = 0 To .NumRows - 1
                For c As Integer = 0 To .NumCols - 1
                    If .PageContents(sclPage.Value).Item(c, r).StartsWith(CALIBRATIONSTRING) Then
                        GetCombo(c, r).Text = CALIBRATIONSTRING
                    Else
                        GetCombo(c, r).Text = .PageContents(sclPage.Value).Item(c, r)
                    End If
                Next
            Next
        End With
    End Sub

    Private Sub UpdateCaption()
        grpPreview.Text = String.Format("Preview && Pane Selection (Page {0} of {1}):", sclPage.Value + 1, sclPage.Maximum + 1)
    End Sub

End Class